package com.hd123.rumba.gwt.widget2.client.misc;

import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.HTML;

/**
 * 伪链接，样式模拟普通的HTML链接（例如字体为蓝色、鼠标悬停时显示下划线等），并允许处理点击事件（ClickListener
 * ）。
 * <p>
 * 
 * <b>CSS Style Rules</b> <ol type=disc>
 * <li>.rb-Hyperlink {}</li>
 * <li>.rb-Hyperlink-hover { 鼠标悬停状态 }</li>
 * <li>.rb-Hyperlink-disabled { 不可用状态 }</li> </ol>
 * 
 * @author LiQi
 * 
 */
@SuppressWarnings("deprecation")
public class RHyperlink extends HTML {

  private static final String STYLENAME = "rb-Hyperlink";
  private static final String DEPENDENT_STYLENAME_HOVER = "hover";
  private static final String DEPENDENT_STYLENAME_DISABLED = "disabled";

  public RHyperlink() {
    super();
    setStyleName(STYLENAME);

    HyperlinkMouseHandler mouseHandler = new HyperlinkMouseHandler();
    addMouseOverHandler(mouseHandler);
    addMouseOutHandler(mouseHandler);

    enabled = true;
  }

  /**
   * @param html
   *          链接的文字内容
   */
  public RHyperlink(String html) {
    this();
    setHTML(html);
  }

  /**
   * @param html
   *          链接的文字内容
   * @param listener
   *          点击事件处理
   * 
   * @deprecated 请用{@link #RHyperlink(String, ClickHandler)}代替
   */
  @Deprecated
  public RHyperlink(String html, ClickListener listener) {
    this(html);
    addClickListener(listener);
  }

  /**
   * @param html
   *          链接的文字内容
   * @param handler
   *          点击事件处理
   */
  public RHyperlink(String html, ClickHandler handler) {
    this(html);
    addClickHandler(handler);
  }

  private boolean enabled;

  /**
   * 取得当前是否可用。
   * 
   * @return
   */
  public boolean isEnabled() {
    return enabled;
  }

  /**
   * 设置当前可用状态。
   * 
   * @param enabled
   */
  public void setEnabled(boolean enabled) {
    this.enabled = enabled;
    if (enabled) {
      removeStyleDependentName(DEPENDENT_STYLENAME_DISABLED);
    } else {
      addStyleDependentName(DEPENDENT_STYLENAME_DISABLED);
    }
  }

  public void onBrowserEvent(Event event) {
    switch (DOM.eventGetType(event)) {
    case Event.ONCLICK:
      if (!enabled) {
        event.preventDefault();
        return;
      }
      break;
    }
    super.onBrowserEvent(event);
  }

  /**
   * 鼠标事件处理
   * 
   * @author LiQi
   * 
   */
  private class HyperlinkMouseHandler implements MouseOverHandler, MouseOutHandler {

    public void onMouseOver(MouseOverEvent event) {
      if (enabled)
        addStyleDependentName(DEPENDENT_STYLENAME_HOVER);
    }

    public void onMouseOut(MouseOutEvent event) {
      if (enabled)
        removeStyleDependentName(DEPENDENT_STYLENAME_HOVER);
    }
  }
}
